package com.diors.commons.network;

import java.util.concurrent.atomic.AtomicInteger;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;

/**
 * 通信建立的连接超类
 * @author	darren.ouyang
 * @data	2013-9-9
 */
public abstract class DiorsConnection 
{

	private final static AtomicInteger increment = new AtomicInteger(1); 

	private int connID;
	
	/* 连接 */
	ChannelHandlerContext channel;
	
	/* 调度器 */
	Dispatcher dispatcher;

	/* IP地址 */
	String ip;

	/* 读取流 */
	ChannelBuffer readBuffer;

	/* 写入流 */
	ChannelBuffer writeBuffer;
	
	/* 对象内置锁 */
	protected final Object guard = new Object();
	
	/* 连接是否已经关闭。 */
	protected boolean closed = Boolean.FALSE;
	
	public DiorsConnection ()
	{
		connID = increment.getAndIncrement();
	}
	
	public int getConnID ()
	{
		return connID;
	}
	
	/**
	 * 获取IP地址
	 * @return
	 * @create	2013-9-10	darren.ouyang
	 */
	public String getIP ()
	{
		return ip;
	}
	
	protected abstract ReceivablePacket createReceivableRacket (DiorsBuffer dbuffer);
	
	protected final boolean isWrite ()
	{
		return closed || !getChannel().isOpen();
	}
	
	/**
	 * 发送数据包
	 * @param buffer
	 * @return
	 * @create	2013-9-10	darren.ouyang
	 */
	protected final boolean writeData (DiorsBuffer buffer)
	{
		getChannel().write(buffer.buffer);
		return Boolean.TRUE;
	}
	
	private Channel getChannel()
	{
		return channel.getChannel();
	}

	/**
	 * 链接关闭
	 * @param con	链接实体
	 * @create 2013-9-15
	 */
	public abstract void connectionClose ();
}
